// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  const count=await db.collection('QandA').count();      //集合的总长度
  //console.log(count)
  var total=count.total;
  //console.log(total)
  var numArray=new Array();
  for(var i=0;i<total;i++){
    numArray.push(i)     //0到total的数
  }
  var randomArray=new Array();
  for (var i = 0; i < 10; i++) {   //获取 十个0到count的随机数 
    var site = (Math.random() * (numArray.length-1)).toFixed(0);  //优化了取数方法，避免出现重复数字
    randomArray[i] =numArray.splice(site,1).toString();  
  }
  const rst = await db.collection('QandA').where({   //根据随机数在集合QandA中随机抽取10道题目
    number: _.in(randomArray)
    })
    .limit(10)
    .get();
  return {
    rst:rst,
    randomArray: randomArray
    }
}